<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>进出记录</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<!--标准mui.css-->
		<link rel="stylesheet" href="../css/mui.min.css">
		<link rel="stylesheet" type="text/css" href="../css/mui.picker.min.css" />
		<!--App自定义的css-->
		<link rel="stylesheet" type="text/css" href="../css/common.css"/>
		<style>
			.fl-r{
				float: right;
			}
			#devices{
				margin-right: 1rem;
			}
			.perhead img{
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%,-50%);
				width: 2rem;
				height: 2rem;
				overflow: hidden;
			}
			.list-ul{
				padding: 0rem .5rem;
			}
			.mb-0{
				margin-bottom: 0;
			}
			.time-ul li .perhead{
				position: relative;
			}
		</style>
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left" id="firBack"></a>
			<h1 class="mui-title">进出记录</h1>
		</header>
		<div class="mui-content mui-scroll-wrapper"> 
			<ul>
			    <li class="search-li">
			    	<div class="search-box"> 
					    <input type="search" placeholder="请输入房屋名称/租客姓名">
						<button type="button">查询</button>
			    	</div>
			    </li>
			    <li class="time-ul">
			    	<div class="limit-time mb-0">
	    				<a id='startTime' class="btn">开始时间</a>
	    				<span>至</span>
	    				<a id='endTime'  class="btn">结束时间</a>	
	    				<a class="fl-r" id="devices" data-view="deviceList.html">所有设备</a>
	    			</div>
			    </li>
			    <li>
			    	<ul class="time-ul list-ul" id="recList">
					</ul>
			    </li> 
			</ul>
		</div>
		<script src="../js/mui.min.js"></script>
		<script src="../js/app.js"></script>
		<script src="../js/md5.js"></script>
		<script src="../js/jquery.js"></script>
		<script src="../js/mui.picker.min.js"></script>
		<script>
			mui.init({
				swipeBack:true, //启用右滑关闭功能
				pullRefresh:{
				    container:".mui-content",//待刷新区域标识
				    down:{
				    	callback:pullRefresh
				    },
				    up:{
				      height:50,	//可选.默认50.触发上拉加载拖动距离
				      auto:false,	//可选,默认false.自动上拉加载一次
				      contentrefresh:"正在加载...",	//可选，正在加载状态时，上拉加载控件上显示的标题内容
				      contentnomore:'没有更多数据了',		//可选，请求完毕若没有更多数据时显示的提醒内容；
				      callback:pullLoading 	//必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
				    }
				    
				}
			});
			
			//第一层页面自定义返回按钮操作
			document.getElementById("firBack").addEventListener('tap',function(){
				window.android.finish();
			})
			
			var mobileNum = getUrlMobile('mobile');
			localStorage.setItem('mobile',mobileNum);
			function formatDateTime(type,time) {    //生成年月日时分秒
				if(time){
					var date = new Date(time);
				}else{
					var date = new Date();  
				}
			    var y = date.getFullYear();    
			    var m = date.getMonth() + 1;    
			    m = m < 10 ? ('0' + m) : m;    
			    var d = date.getDate();    
			    d = d < 10 ? ('0' + d) : d;    
			    var h = date.getHours();  
			    h = h < 10 ? ('0' + h) : h;  
			    var minute = date.getMinutes();  
			    var second = date.getSeconds();  
			    minute = minute < 10 ? ('0' + minute) : minute;    
			    second = second < 10 ? ('0' + second) : second;
			    if(type === 'date'){
			    	return y+'-'+ m +'-'+d;    
			    }else{
			    	return y+''+ m +''+d +''+h+''+minute+''+second;    
			    }
			};
			var key = 'udacs!@#';//固定的key值
			var mobile = localStorage.getItem('mobile');
//			var mobile = '13580524435';	 
			var timestamp = formatDateTime();//年月日时分秒
			var token = mobile + timestamp + key;//token的拼接
			var md5 = hex_md5(token);//token的ma5加密
			var q_word='';
			var device_id='';
			var start_date = formatDateTime('date',(new Date() - 7*24*60*60*1000));
			var end_date = formatDateTime('date');
			var startTime = 0; 
			var endTime = new Date();
			var buildingList = [];
			var totalPage; //用于存放返回的总页数
			var i = 2;//用于上拉加载时发送的页数
			getInOutRec();
			var inOutType = {0:'刷卡开门',1:'app开门',2:'后台开门',3:'室内按钮开门'};
			//获取进出记录
			function getInOutRec(loadPage){
				var page = loadPage || 1;
				$.ajax(httpUrl+'get_door_rec',{
					data:JSON.stringify({
						"auth":{ 
							"mobile":mobile,
							"token":md5,
							"imei":"imei",
							"imsi":"imsi",
							"timestamp" :timestamp
						},
				   		"api_ver":"1",
						"req":{
							"mobile":mobile ,
							"q_word": q_word,
							"device_id": device_id,
							"start_date":start_date,
							"end_date":end_date,
							"page": page
						}
					}),
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					contentType: "text/plain; charset=utf-8",					
					success:function(data){
						buildingList = [];
						if(!loadPage){
							i=2; 
							totalPage = data.rsmsg.total_page;
							document.getElementById('recList').innerHTML = '';
						}
						var text = '<li><div class="perhead"><img class="mui-media-object mui-pull-left" src="../images/icon_passout.png"></div><div class="mui-media-body"';
						mui.each(data.resp, function(key,item) {
							buildingList[key] = item.building;
							var inOutResult = '';
							if(item.inOutResult == 0){
		                    	inOutResult = item.date +'<span class="fl-r" style="color:blue">成功</span>';
		                    }else if(item.inOutResult == 1){
		                    	inOutResult = item.date +'<span class="fl-r" style="color:red">失败</span>';
		                    }
							document.getElementById('recList').insertAdjacentHTML('beforeEnd',
							text + ' data-id="'+ item.rec_id +'" data-type="'+ item.inOutType +'"><p class="mui-ellipsis">'+ item.user +'<span class="fl-r">'+ inOutType[item.inOutType] +'</span></p><p class="mui-ellipsis">'+ inOutResult +'</p></div></a></li>'); 
						}); 
						clearEffect();
					},
					error:function(xhr,type,errorThrown){
						mui.toast('网络异常或者服务器出错：'+type,{duration:'2000',type:'div'});
						clearEffect();
					}
				})
			}
			
			var domID = '';
			mui(".limit-time").on('tap','.btn',function(){
				domID = this.getAttribute('id');
				if(domID === "startTime"){
					startTime = 0;
				}
				var dtpicker = new mui.DtPicker({
				    type: "date",//设置日历初始视图模式 
				    beginDate: startTime,//设置开始日期 
				    endDate: endTime,//设置结束日期 
				    labels: ['年', '月', '日'],//设置默认标签区域提示语 
				})
				
				dtpicker.show(function(endTime_record) {
				    var time = endTime_record.value.slice(0,10);
				    var startTimeDom = document.getElementById('startTime');
				    var endTimeDom = document.getElementById('endTime');
				    if(domID=== "startTime"){
				    	startTimeDom.innerHTML = time;
				    	startTime = new Date(time);
				    	
				    }else{
				    	endTimeDom.innerHTML = time;
				    	endTime = new Date();
				    	end_date = endTimeDom.innerHTML;
				    }
				    if(startTimeDom.innerHTML === "开始时间"){
				    	newStartTime = new Date(Date.parse(endTimeDom.innerHTML.replace(/-/g,  "/"))).getTime();
				    	start_date = formatDateTime('date',(newStartTime - 7*24*60*60*1000));
				    }else{
				    	start_date = startTimeDom.innerHTML;
				    	
				    }
				    getInOutRec();
				}) 
			})
			
			//搜索功能
			mui(".search-li").on('tap','button',function(){
				q_word = document.getElementsByTagName('input')[0].value;
				getInOutRec();
			})
			
			//选择设备
	        mui(".limit-time").on('tap','#devices',function(){
	        	localStorage.setItem('inAndOut_buildingList',JSON.stringify(buildingList));
				mui.openWindow({
				    url:'deviceList.html',
				    id:'deviceList.html'
				});
			}) 
			
			//监听选择的设备类型并查询
			window.addEventListener('storage',function (e) {//e只是一个传参
                //获取被修改的键值
                if (e.key == 'inAndOut_deviceType') {
                	q_word = e.newValue;
                	getInOutRec();
                }
          	})
	        
	        //查看记录详情
	        mui(".mui-content").on('tap','.mui-media-body',function(){
			  //获取ID和类型
				var inAndOut_detail = {};
				inAndOut_detail.id = this.getAttribute('data-id');
				inAndOut_detail.inOutType = this.getAttribute('data-type');
				localStorage.setItem('inAndOut_detail',JSON.stringify(inAndOut_detail));
				mui.openWindow({
				    url:'inAndOutDetail.html',
				    id:'inAndOutDetail.html'
				});
			})
	        
	        //上拉加载更多数据
	        function pullLoading() {
	        	setTimeout(function() {
	        		if(i <= totalPage){
	        			getInOutRec(i);
			     		i++;
	        		}else{
	        			clearEffect();
	        			mui.toast('没有更多的数据',{duration:'2000',type:'div'});
	        		}
			     	
			     },1500) 
			}
	        
	        //下拉刷新数据
	        function pullRefresh(){
	        	setTimeout(function() {
	        		getInOutRec();
	        	},1500)
	        }
	        
	        //清除下拉刷新和上拉加载数据效果
	        function clearEffect(){
	        	mui('.mui-content').pullRefresh().endPulldownToRefresh();
				mui('.mui-content').pullRefresh().endPullupToRefresh();
	        }
		</script>
	</body>

</html>